package Controller

import (
	"backend/Dao"
	"backend/Service/dbService"
	"fmt"
	"github.com/gin-gonic/gin"
	"strconv"
)

type CurriculumSeriesController struct {
}

type newCurriculumSeries struct {
	CurriculumSeriesName     string
	CurriculumSeriesDescribe string
}

//
// SetNewCurriculumSeries
// @Description: 设置新的课程序列
// @author MaTaoXun 2022-01-15 16:58:20
// @return gin.HandlerFunc
//
func (this CurriculumSeriesController) SetNewCurriculumSeries(c *gin.Context) {
	var data = newCurriculumSeries{}
	err := c.BindJSON(&data)
	if err != nil {
		fmt.Println("err", err)
	}
	dbService.DbConn.Create(&Dao.CurriculumSeries{
		Model:                    Dao.GetModel(),
		CurriculumSeriesName:     data.CurriculumSeriesName,
		CurriculumSeriesDescribe: data.CurriculumSeriesDescribe,
	})
	c.String(200, "新建成功")
}

//
// GeyCurriculumSeries
// @Description: 获取所有课程序列
// @author MaTaoXun 2022-01-15 16:59:09
// @return gin.HandlerFunc
//
func (this CurriculumSeriesController) GeyCurriculumSeries(c *gin.Context) {
	var series []Dao.CurriculumSeries
	dbService.DbConn.Find(&series)
	c.JSON(200, series)
}

//
// DeleteCourseSeries
// @Description: 删除课程序列,其下课程以及课程章节,作业,作业文件
// @author MaTaoXun 2022-01-15 16:59:24
// @return gin.HandlerFunc
//
func (this CurriculumSeriesController) DeleteCourseSeries(c *gin.Context) {
	id := c.Query("id")
	idInt, _ := strconv.Atoi(id)
	fmt.Println(idInt)
	seriesModel := &Dao.CurriculumSeries{Model: Dao.Model{ID: uint(idInt)}}
	//删除series
	dbService.DbConn.Delete(seriesModel)
	//根据seriesid 删除 curriculum
	var curriculumList []Dao.Curriculum
	dbService.DbConn.Where("curriculum_series_id = ?", idInt).Find(&curriculumList)
	dbService.DbConn.Where("curriculum_series_id = ?", idInt).Delete(&Dao.Curriculum{})
	//根据curriculum_id删除homework
	for _, curriculum := range curriculumList {
		//删除chapter
		dbService.DbConn.Where("curriculum_id = ?", curriculum.ID).Delete(&Dao.Chapter{})

		var HomeWorkList []Dao.Homework
		dbService.DbConn.Where("curriculum_id = ?", curriculum.ID).Find(&HomeWorkList)
		dbService.DbConn.Where("curriculum_id = ?", curriculum.ID).Delete(&Dao.Homework{})
		//根据HomeWorkid删除homeWorkfile
		for _, homework := range HomeWorkList {
			dbService.DbConn.Where("homework_id = ?", homework.ID).Delete(&Dao.HomeworkFile{})
		}
	}
	c.String(200, "delSuc")
}

//
// SetCurrSeriesIntroduction
// @Description: 设置课程序列的简介
// @author MaTaoXun 2022-01-15 17:00:36
// @return gin.HandlerFunc
//
func (this CurriculumSeriesController) SetCurrSeriesIntroduction(c *gin.Context) {
	data := struct {
		SeriesId     int    `json:"seriesId,string"`
		Introduction string `json:"introduction"`
	}{}
	c.BindJSON(&data)
	dbService.DbConn.Model(&Dao.CurriculumSeries{
		Model: Dao.Model{ID: uint(data.SeriesId)},
	}).Updates(Dao.CurriculumSeries{
		CurriculumSeriesDescribe: data.Introduction,
	})
	c.String(200, "ok")
}
